﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Server.Framework.Message
{
    /// <summary>
    /// Author: Leil
    /// Description: 消息类型管理类
    /// CreateTime: 2020/5/11 17:32:18
    /// </summary>
    class MessageTypeManager
    {

        private static readonly Dictionary<int, Type> msgTypeDic = new Dictionary<int, Type>();

        /// <summary>
        /// 初始化所有消息类型到字典
        /// </summary>
        public static void Init()
        {
            Type[] typeArr = Assembly.GetExecutingAssembly().GetTypes();
            for (int i = 0; i < typeArr.Length; i++)
            {
                Type type = typeArr[i];

                object[] attributes = type.GetCustomAttributes(true);
                object[] messageAttrs = attributes.Where(attribute => attribute is MessageAttr).ToArray();
                if (messageAttrs.Length > 0)
                {
                    MessageAttr messageAttr = messageAttrs.First() as MessageAttr;
                    msgTypeDic.Add(messageAttr.MessageId, type);
                }
            }
        }

        /// <summary>
        /// 根据消息号获取Type
        /// </summary>
        /// <param name="messageId">消息号</param>
        /// <returns>消息体类型</returns>
        public static Type GetType(int messageId)
        {
            if (msgTypeDic.ContainsKey(messageId))
            {
                return msgTypeDic[messageId];
            }
            return null;
        }


    }
}
